package cn.lzx.hrm.service.impl;

import cn.lzx.doc.CourseDoc;
import cn.lzx.exctption.GlobalException;
import cn.lzx.hrm.ai.IAIContentAuditService;
import cn.lzx.hrm.client.CourseDocClient;
import cn.lzx.hrm.config.RabbitMQConfig;
import cn.lzx.hrm.domain.*;
import cn.lzx.hrm.dto.CourseDto;
import cn.lzx.hrm.enums.CourseGrade;
import cn.lzx.hrm.mapper.*;
import cn.lzx.hrm.query.CourseQuery;
import cn.lzx.hrm.service.ICourseService;
import cn.lzx.util.AjaxResult;
import cn.lzx.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzx
 * @since 2022-01-06
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private IAIContentAuditService aiContentAuditService;
    @Autowired
    private CourseAuditLogMapper courseAuditLogMapper;
    @Autowired
    private CourseDocClient courseDocClient;
    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Autowired
    private CourseOnlineLogMapper courseOnlineLogMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;




    @Override
    public PageList<Course> selectPageList(CourseQuery query) {
        Page<Course> page = new Page<>(query.getPage(), query.getRows());
        List<Course> datas = courseMapper.loudPageList(page, query);
        return new PageList<>(page.getTotal(),datas);
    }

    @Override
    public void updateById(CourseDto courseDto) {
        Course course = courseDto.getCourse();
        CourseDetail courseDetail = courseDto.getCourseDetail();
        CourseMarket courseMarket = courseDto.getCourseMarket();
        CourseGrade grade =CourseGrade.getGrade(course.getGradeId());
        if (grade==null) {
            throw new GlobalException("请填写课程基本信息");
        }
        String content = course.getName()+" "+ course.getForUser()+" "+ courseDetail.getIntro()+" "+ courseDetail.getDescription();
        AjaxResult ajaxResult = aiContentAuditService.audit(content, null, null);
        int status = ajaxResult.isSuccess()?1:-1;
        //2 正在操作
        //修改课程
        course.setStatus(status);
        courseMapper.updateById(course);
        //修改市场信息
        courseMarketMapper.updateById(courseMarket);
        //修改课程详情
        courseDetailMapper.updateById(courseDetail);
        //3 进行百度内容自动审核
        auditHandle(ajaxResult.getMessage(),course);

    }

    private void auditHandle(String message, Course course) {
        CourseAuditLog auditLog = course2CourseAuditLog(course,message);
        courseAuditLogMapper.insert(auditLog);
    }

    /**
     * 添加审核日志
     * @param course
     * @param message
     * @return
     */
    private CourseAuditLog course2CourseAuditLog(Course course, String message) {
        CourseAuditLog auditLog = new CourseAuditLog();
        auditLog.setCourseId(course.getId());
        auditLog.setCourseName(course.getName());
        auditLog.setState(course.getStatus());
        String note = course.getStatus()!=-1 ?"审核通过": message;
        auditLog.setNote(note);
        auditLog.setAuditTime(new Date());
        auditLog.setAuditAdminId(null);
        auditLog.setAuditAdminName("系统自动审核");
        return auditLog;
    }

    @Override
    public void insert(CourseDto courseDto) {
        Course course = courseDto.getCourse();
        CourseDetail courseDetail = courseDto.getCourseDetail();
        CourseMarket courseMarket = courseDto.getCourseMarket();
        if (course==null) {
            throw new GlobalException("请填写课程基本信息");
        }
        if (courseDetail==null) {
            throw new GlobalException("请填写课程详情");
        }
        if (courseMarket==null) {
            throw new GlobalException("请填写课程营销信息");
        }
//        以后会直接调用百度的自动审核接口 我们目前不做
        String content = course.getName()+" "+ course.getForUser()+" "+ courseDetail.getIntro()+" "+ courseDetail.getDescription();
        AjaxResult ajaxResult = aiContentAuditService.audit(content, null, null);
        //添加课程
        int status = ajaxResult.isSuccess()?1:-1;
        course.setStatus(status);
        courseMapper.insert(course);
        //添加课程明细
        Long id = course.getId();
        courseDetail.setId(id);
        courseDetailMapper.insert(courseDetail);
        //添加营销信息
        courseMarket.setId(id);
        courseMarketMapper.insert(courseMarket);
        //3 进行百度内容自动审核
        auditHandle(ajaxResult.getMessage(),course);
    }

    /**
     * 上线
     * @param ids
     * @return
     */
    
    @Override
    public AjaxResult online(List<Long> ids) {
        if (ids==null) {
            throw new GlobalException("请选择数据再操作");
        }
        courseMapper.online(ids);
        //3 远程调用feign接口，实现添加ES数据
        List<CourseDoc> courseDocs = new ArrayList<>();
        List<CourseOnlineLog> courseOnlineLogs = new ArrayList<>();
        //课程推送
        for (Long courseId :ids){
            //保存es文档为course
            CourseDoc courseDoc = new CourseDoc();
            Course course = courseMapper.selectById(courseId);
            BeanUtils.copyProperties(course,courseDoc);
            //保存课程类型
            Long courseTypeId = course.getCourseTypeId();
            CourseType courseType = courseTypeMapper.selectById(courseTypeId);
            courseDoc.setCourseTypeName(courseType.getName());
            //保存营销信息
            CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
            BeanUtils.copyProperties(courseMarket,courseDoc);
            courseDocs.add(courseDoc);
            //处理上下线日志
            CourseOnlineLog log = course2OnlineLog(course);
            courseOnlineLogs.add(log);
        }
        courseDocClient.batchAdd(courseDocs);
        //4 上线历史记录。
        courseOnlineLogMapper.batchSave(courseOnlineLogs);
        //课程推送方法
        publishMessage(ids);
        return AjaxResult.me();
    }

    /**
     * 课程推送
     * @param ids
     */

    private void publishMessage(List<Long> ids) {
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,"massage.sms",ids);
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,"massage.email",ids);
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC,"massage.system",ids);
    }

    private CourseOnlineLog course2OnlineLog(Course course) {
        //声明一个日志对象
        CourseOnlineLog log = new CourseOnlineLog();
        //日志的id就是课程的id 名字  设置状态为上线 1 设置上线时间为当前时间 处理人不管
        log.setCourseId(course.getId());
        log.setCourseName(course.getName());
        log.setState(1);
        log.setOnlineTime(new Date());
        return log;
    }

    /**
     * 下线
     * @param ids
     * @return
     */
    @Override
    public AjaxResult offline(List<Long> ids) {
        if (ids==null){
            throw new GlobalException("请选择数据再操作");
        }
        courseMapper.offline(ids);
        //3 远程调用feign接口，实现删除ES数据
        courseDocClient.batchDel(ids);
        //4 下线历史记录。
        batchOffLineLog(ids);
        return AjaxResult.me();
    }

    private void batchOffLineLog(List<Long> ids) {
        List<CourseOnlineLog> courseOnlineLogs = ids.stream().map(id -> {
            Course course = courseMapper.selectById(id);
            CourseOnlineLog log = new CourseOnlineLog();
            log.setCourseId(course.getId());
            log.setCourseName(course.getName());
            //下线
            log.setState(0);
            log.setOfflineTime(new Date());
            return log;
        }).collect(Collectors.toList());
        courseOnlineLogMapper.batchSave(courseOnlineLogs);
    }

    @Override
    public boolean deleteById(Serializable courseId) {
        //删除详情
        courseDetailMapper.deleteById(courseId);
        //删除营销信息
        courseMarketMapper.deleteById(courseId);
        //删除课程信息
        courseMapper.deleteById(courseId);
        //是否删除审核日志，上下架日志，看你的业务逻辑
        return  true;
    }


}
